<script setup lang="ts">
import * as echarts from 'echarts/core'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components'
import { LineChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { onMounted } from 'vue'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { getExericseRecordByDateListUtil } from '@/AGC/utils/record'
import dayjs from 'dayjs'
import type { ExerciseRecordI } from '@/types/record'
import { useUserStore } from '@/stores/user'
import { getWeekByDate } from '@/utils'
import type { TooltipFormatterParams } from '@/types/chart'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
])
const router = useRouter()
const isShow = ref(false)
const isShowDay = ref(false)
const chartRef = ref()
let chart: echarts.ECharts | null = null
// 初始化图表
const initEcharts = () => {
  chart = echarts.init(chartRef.value)
  const option = {
    title: {
      text: '本周训练情况',
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params: TooltipFormatterParams[]) {
        let result = ''

        params.forEach((param) => {
          result = `${param.name} 消耗热量: ${param.value}千卡<br/>`

          switch (param.name) {
            case '周一':
              weekRecordList[0].forEach((item) => {
                result += `${item.exercise_name} ${item.amount_unit} ${item.calories}千卡<br/>`
              })
              break
            case '周二':
              weekRecordList[1].forEach((item) => {
                result += `${item.exercise_name} ${item.amount_unit} ${item.calories}千卡<br/>`
              })
              break
            case '周三':
              weekRecordList[2].forEach((item) => {
                result += `${item.exercise_name} ${item.amount_unit} ${item.calories}千卡<br/>`
              })
              break
            case '周四':
              weekRecordList[3].forEach((item) => {
                result += `${item.exercise_name} ${item.amount_unit} ${item.calories}千卡<br/>`
              })
              break
            case '周五':
              weekRecordList[4].forEach((item) => {
                result += `${item.exercise_name} ${item.amount_unit} ${item.calories}千卡<br/>`
              })
              break
            case '周六':
              weekRecordList[5].forEach((item) => {
                result += `${item.exercise_name} ${item.amount_unit} ${item.calories}千卡<br/>`
              })
              break
            case '周日':
              weekRecordList[6].forEach((item) => {
                result += `${item.exercise_name} ${item.amount_unit} ${item.calories}千卡<br/>`
              })
              break
          }
        })

        return result
      },
    },
    legend: {
      selectedMode: false,
      data: ['运动'],
    },
    grid: {
      left: '3%',
      bottom: '3%',
      containLabel: true,
    },
  }
  chart.setOption(option)
}
// 更新图表
const updateEcharts = () => {
  const options = {
    xAxis: {
      type: 'category',
      name: '星期',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLine: {
        symbol: ['none', 'arrow'],
        symbolOffset: [0, 10],
      },
    },
    yAxis: {
      type: 'value',
      name: '消耗热量(千卡)',
      axisLine: {
        show: true,
        symbol: ['none', 'arrow'],
        symbolOffset: [0, 10],
      },
    },
    series: [
      {
        name: '运动',
        type: 'line',
        stack: 'Total',
        data: weekCalories,
      },
    ],
  }

  chart?.setOption(options)
}
// 更新 isShow && isShowDay
const updateIsShow = () => {
  // 获取用户数据
  const user = {
    isShow: false,
    isShowDay: true,
  }
  // 判断是否要显示图表内容
  isShow.value = user.isShow
  isShowDay.value = user.isShowDay
}
updateIsShow()
onMounted(async () => {
  setTimeout(async () => {
    await getRecordList()
    initEcharts()

    if (recordList.value.length > 0) {
      updateEcharts()
    }
  }, 100)
})
// 去收集本周数据的点击事件
const collectWeekDate = () => {
  router.push({ path: '/record', query: { type: '运动' } })
}
const dateString = ref(dayjs().format('YYYY-MM-DD'))
// 今天运动记录
const todayRecord = ref<ExerciseRecordI>({
  id: 0,
  user_id: useUserStore().userInfo.id,
  date: dayjs().format('YYYY-MM-DD'),
  exercise_name: '',
  amount_unit: '',
  calories: 0,
})
// 本周运动消耗热量
const weekCalories: number[] = []
// 获取本周运动消耗热量
const getWeekCalories = async () => {
  const dateList = getWeekByDate(dateString.value)

  for (let i = 0; i < dateList.length; i++) {
    let calories = 0

    recordList.value.forEach((item) => {
      if (item.date == dateList[i]) {
        calories += item.calories
      }
    })

    weekCalories.push(calories)
  }
}
// 获取本周运动记录 => 按天分组
const weekRecordList: ExerciseRecordI[][] = []
const getWeekRecordByDay = () => {
  const dateList = getWeekByDate(dateString.value)

  for (let i = 0; i < dateList.length; i++) {
    const tempList: ExerciseRecordI[] = []

    recordList.value.forEach((item) => {
      if (item.date == dateList[i]) {
        tempList.push(item)
      }
    })

    weekRecordList.push(tempList)
  }
}
// 运动记录
const recordList = ref<ExerciseRecordI[]>([])
const getRecordList = async () => {
  // 获取运动记录
  const data = await getExericseRecordByDateListUtil(dateString.value)
  recordList.value = data
  // 获取本周运动消耗热量
  await getWeekCalories()
  // 获取本周运动记录
  getWeekRecordByDay()
  // 获取今天运动记录
  const result = data.find((item) => item.date == dateString.value)

  if (result) {
    todayRecord.value = result
  }
}
</script>

<template>
  <el-card style="width: 100%; position: relative">
    <div v-if="recordList.length == 0" class="gradient-text">
      <div class="keyword">📢小康途</div>
      还没有收集到您
      <div class="keyword">本周</div>
      的运动数据哦~
      <div class="link" @click="collectWeekDate">去收集</div>
    </div>
    <div v-else-if="todayRecord.id == 0" class="gradient-day-text">
      <span>📢</span>
      <span class="keyword">小康途</span>
      还没有收集到您
      <span class="keyword">今天</span>
      的运动数据哦~
      <span class="link" @click="collectWeekDate">去收集</span>
    </div>
    <div v-else class="gradient-day-text">
      <span>📢</span>
      <span class="keyword">小康途</span>
      已经收集到您
      <span class="keyword">今天</span>
      的运动数据了~
      <span class="link" @click="collectWeekDate">去修改</span>
    </div>
    <div ref="chartRef" style="width: 100%; height: 400px"></div>
  </el-card>
</template>

<style scoped lang="less">
// 收集本周数据提示
.gradient-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
  color: black;
  font-size: 45px;
  text-align: center;
  font-family: 'Comic Sans MS', cursive, sans-serif;

  .keyword {
    color: rgb(5, 88, 229); /* 高亮颜色 */
    font-weight: bold; /* 加粗 */
  }

  .link {
    text-decoration: underline; /* 下划线 */
    cursor: pointer; /* 鼠标指针 */
  }

  .link:hover {
    color: rgb(5, 88, 229); /* 鼠标悬停时的颜色 */
  }
}
// 收集今天数据提示
.gradient-day-text {
  position: absolute;
  left: 84%;
  top: 12px;
  transform: translateX(-5%);
  z-index: 99;
  background: linear-gradient(135deg, #ff9a9e, #fad0c4);
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  max-width: 250px;
  color: white;
  font-size: 14px;
  text-align: center;
  font-family: 'Comic Sans MS', cursive, sans-serif;

  .keyword {
    color: #ffeb3b; /* 高亮颜色 */
    font-weight: bold; /* 加粗 */
  }

  .link {
    text-decoration: underline; /* 下划线 */
    cursor: pointer; /* 鼠标指针 */
  }

  .link:hover {
    color: #ffeb3b; /* 鼠标悬停时的颜色 */
  }
}
</style>
